//
//  EditViewController.m
//  随手记
//
//  Created by Medalands on 15/11/5.
//  Copyright (c) 2015年 Medalands. All rights reserved.
//

#import "EditViewController.h"
#import "HSDatePickerViewController.h"
#import "MoneyTypeViewController.h"
#import "CategoryView.h"
#import "AccountModel.h"
#import "FMDBModel.h"
#import "Singleton.h"

@interface EditViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,HSDatePickerViewControllerDelegate>

@property (nonatomic , strong) UITableView *tmpTableView;
@property (nonatomic , strong) UIButton *categoryButton; // 选择消费项目
@property (nonatomic , strong) UITextField *moneyField; // 具体费用
@property (nonatomic , strong) UITextField *addressTextField; // 地点
@property (nonatomic, strong) NSDate *selectedDate;
// -- 时间
@property (nonatomic , strong) UILabel *timeLable;
@property (nonatomic , strong) UILabel *typeLabel; // 货币符号
@property (nonatomic , assign) BOOL isClosed;
@property (nonatomic , strong) CategoryView *categorty;
@property (nonatomic , strong) UIView *shadowView;
@property (nonatomic , strong) UITapGestureRecognizer *tap;
// -- 付费总金额
@property (nonatomic , strong) UITextField *totalField; // 付费金额
@property (nonatomic , strong) UITextField *consumptionField; // 消费内容
@property (nonatomic , strong) UIView *tmpView;
@property (nonatomic , strong) UIView *tmpTextField;

@property(nonatomic,strong)AccountModel *account;
@end

@implementation EditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"添加账目信息"];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"储存" style:(UIBarButtonItemStyleDone) target:self action:@selector(rightButton)];
    
    self.account = [[AccountModel alloc]init];
    
    self.isClosed = NO;
    self.shadowView = [[UIView alloc ]initWithFrame:KRECT(0, 0, KScreenWidth, KScreenHeight-64)];
    [self.shadowView setBackgroundColor:[UIColor blackColor]];
    self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDidPress:)];
    self.categorty = [[CategoryView alloc] initWithFrame:KRECT(MDXFrom6(100),  KScreenHeight + 20 ,MDXFrom6(150), MDXFrom6(500))];
    [self.view setBackgroundColor:RGBA(242, 242, 242)];
    self.tmpView = [self setUpFirstCellStyle];
    self.tmpTextField = [self setUpAddressTextField];
     self.typeLabel = [[UILabel alloc] initWithFrame:KRECT(110, 0, KScreenWidth - 140, 44)];
    
    NSDate *sendDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY年MM月dd日 HH:mm:ss"];
    NSString *string = [dateFormatter stringFromDate:sendDate];
    
    self.timeLable = [[UILabel alloc] initWithFrame:KRECT(110, 0, KScreenWidth - 120, 44)];
    [self setUpTmpTableView];
    [self.timeLable setText:[NSString stringWithFormat:@"%@",string]];
    self.totalField = [[UITextField alloc] initWithFrame:KRECT(100, 0, KScreenWidth -110, 44)];
    [self.totalField setText:[NSString stringWithFormat:@"%0.2f",0.00]];
    
    self.consumptionField = [[UITextField alloc] initWithFrame:KRECT(100, 0, KScreenWidth -110, 44)];
    [self.consumptionField setPlaceholder:@"未填写"];
    [self setUpCategoryButtonTitle];
    
    // 回收键盘
    [self returnTheKeyboard];
}

- (void)rightButton
{
    if (self.account.total == nil) {
        Singleton *single = [Singleton shareSingle];
        self.account.category = single.category;
        
        self.account.type = self.typeLabel.text;
        self.account.time = self.timeLable.text;
        self.account.total = self.totalField.text;
        self.account.consumption = self.consumptionField.text;
        
        if (self.account.total != nil && ![self.account.total isEqualToString:@""] && ![self.account.total isEqualToString:@"0"]) {
            [[FMDBModel defaultFMDBModel] insertAccount:self.account];
        }
    } else {
        [[FMDBModel defaultFMDBModel]UpdataAccountCategory:nil withNewCategory:nil UpdataAccountRests:nil withNewRests:nil UpdataAccountAddress:nil withNewAddress:nil UpdataAccountTime:self.account.time withNewTime:self.timeLable.text UpdataAccountType:self.account.type withNewType:self.typeLabel.text UpdataAccountTotal:self.account.total withNewTotal:self.totalField.text UpdataAccountConsumption:self.account.consumption withNewConsumption:self.consumptionField.text];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

// 点击空白处,回收键盘
- (void)returnTheKeyboard
{
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到当前view
    [self.view addGestureRecognizer:tapGestureRecognizer];
}


- (void) tapDidPress:(UITapGestureRecognizer *)sender{
    self.isClosed = YES;
    [self.categoryButton sendActionsForControlEvents:(UIControlEventTouchUpInside)];
}

#pragma mark -- TableView
- (void) setUpTmpTableView{

    self.tmpTableView = [[UITableView alloc] initWithFrame:KRECT(0, 0, KScreenWidth, KScreenHeight - 64) style:UITableViewStyleGrouped];
    [self.tmpTableView setDelegate:self];
    [self.tmpTableView setBackgroundColor:[UIColor clearColor]];
    [self.tmpTableView setDataSource:self];
    [self.tmpTableView setTableFooterView:[[UIView alloc] init]];
    [self.view addSubview:self.tmpTableView];
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 4;
    }else
        return 2;
}

#warning  -- 键盘通知
// -- 通知的代理事件（通知）
-(void) registerForKeyboardNotifications{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoradWasShown:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}

#warning --通知事件
- (void) keyBoradWasShown:(NSNotification *)aNotification{

    NSDictionary *info = [aNotification userInfo];

    // 获取键盘高度
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    NSLog(@"%f",kbSize.height);
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    
    self.tmpTableView.contentInset = contentInsets;
    self.tmpTableView.scrollIndicatorInsets = contentInsets;
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    
//     键盘移动 有问题,键盘回收后不返回
    if (!CGRectContainsPoint(aRect, self.totalField.frame.origin)) {
        CGPoint scrollPoint = CGPointMake(0.0, self.totalField.frame.origin.y - kbSize.height);
        [self.tmpTableView setContentOffset:scrollPoint animated:YES];
    }
}

- (void)keyBoardWillBeHidden:(NSNotification *)aNotification{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    self.tmpTableView.contentInset = contentInsets;
    self.tmpTableView.scrollIndicatorInsets = contentInsets;
}

///键盘消失事件
- (void) keyboardWillHide:(NSNotification *)notify {
    // 键盘动画时间
    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //视图下沉恢复原状
    [UIView animateWithDuration:duration animations:^{
        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
}


- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"ID";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:ID];
    }
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0 || indexPath.row == 1) {
            [cell setSelectionStyle:(UITableViewCellSelectionStyleNone)];
            if (indexPath.row == 0) {
                [cell addSubview:self.tmpView];
            }else{
                [cell addSubview:self.tmpTextField];
            }
        }else{
            if (indexPath.row == 3) {
                [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
                [cell.textLabel setText:@"货币符号"];
                [self.typeLabel setTextColor:[UIColor grayColor]];
                [self.typeLabel setTextAlignment:(NSTextAlignmentRight)];
                [self.typeLabel setAdjustsFontSizeToFitWidth:YES];
                [self.typeLabel setText:@"CNY 人民币"];
                [cell addSubview:self.typeLabel];
                
                Singleton *single = [Singleton shareSingle];
                self.typeLabel.text = single.type;
                self.account.type = single.type;
                
            }else{
                 [cell.textLabel setText:@"时间"];
                [self.timeLable setTextColor:[UIColor grayColor]];
                [self.timeLable setTextAlignment:(NSTextAlignmentRight)];
                [self.timeLable setAdjustsFontSizeToFitWidth:YES];
                [cell addSubview:self.timeLable];
                
                Singleton *single = [Singleton shareSingle];
                self.timeLable.text = single.time;
                self.account.time = single.time;
                
            }
        }
    }else{
        if (indexPath.row == 0) {
            [cell setSelectionStyle:(UITableViewCellSelectionStyleNone)];
            [cell.textLabel setText:@"付费金额"];
            [self.totalField setTextAlignment:(NSTextAlignmentRight)];
            self.totalField.keyboardType = UIKeyboardTypeNumberPad;
            [self.totalField setDelegate:self];
            [cell addSubview:self.totalField];
            
            Singleton *single = [Singleton shareSingle];
            self.totalField.text = single.total;
            self.account.total = single.total;
            
        }else{
            [cell setSelectionStyle:(UITableViewCellSelectionStyleNone)];
            cell.textLabel.text = @"消费内容";
            [self.consumptionField setTextAlignment:(NSTextAlignmentRight)];
            [self.consumptionField setDelegate:self];
            [cell addSubview:self.consumptionField];
            
            Singleton *single = [Singleton shareSingle];
            self.consumptionField.text = single.consumption;
            self.account.consumption = single.consumption;
        }
    }
    return cell;
}

#warning -- textField代理事件
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    if (textField == self.totalField) {
        // -- 注册通知事件
       [self registerForKeyboardNotifications];
        [self.totalField setText:@""];
        [self.totalField setPlaceholder:@"请输入付费金额"];
    }else{
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
        
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    }
}


- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}

- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView *tmpView = [[UIView alloc] initWithFrame:KRECT(0, 0, KScreenWidth, 80)];
    [tmpView setBackgroundColor:[UIColor clearColor]];
    UILabel *tmpLabel = [[UILabel alloc] initWithFrame:KRECT(10, 0, KScreenWidth -20, 80)];
    [tmpLabel setBackgroundColor:[UIColor clearColor]];
    [tmpLabel setFont:[UIFont systemFontOfSize:14.0f]];
    [tmpLabel setTextColor:[UIColor grayColor]];
    
    if (section == 1) {
        [tmpLabel setText:@"为方便您的使用，以上选项提供的是一次最新数据的存储!"];
    }else{
        [tmpLabel setText:@"本程序获取的是您的当前时间，您可通过点击时间修改你的时间"];
    }
    
    [tmpView addSubview:tmpLabel];
    [tmpLabel setNumberOfLines:0];
    return tmpView;
}
- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    if (section == 0) {
        return MDXFrom6(40);
    }else
        return MDXFrom6(40);
}

// -- 第一个cell
- (UIView *) setUpFirstCellStyle{
    
    UIView *tmpView = [[UIView alloc] initWithFrame:KRECT(0, 0, KScreenWidth, 44)];
    self.categoryButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.categoryButton setFrame:KRECT(10, 0, 80, 44)];
    [self.categoryButton setTitle:@"  其他" forState:(UIControlStateNormal)];
//    [self.categoryButton setImage:[UIImage imageNamed:@""] forState:(UIControlStateNormal)];
    [self.categoryButton addTarget:self action:@selector(categoryButtonDidPress:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.categoryButton setTitleColor:[UIColor blueColor] forState:(UIControlStateNormal)];
    
    UILabel *tmpLabel = [[UILabel alloc] initWithFrame:KRECT(90, 0, 10, 44)];
    [tmpLabel setTextColor:[UIColor grayColor]];
    [tmpLabel setText:@">"];
    [tmpView addSubview:tmpLabel];
    [tmpView addSubview:([self setUpMoneyTextFieldWith:@"其他" And:KRECT(100,0,KScreenWidth- 100,44)])];
    [tmpView addSubview:self.categoryButton];
    
    return tmpView;
    
}
#warning  -- 点击事件
- (void) categoryButtonDidPress:(UIButton *)sender{
    
    __weak typeof(self) weakSelf = self;
    
    if (self.isClosed) {
        
        [UIView animateWithDuration:0.3 animations:^{
            [weakSelf.categorty setFrame:KRECT(MDXFrom6(100),  KScreenHeight + 20 ,MDXFrom6(150), MDXFrom6(500))];
        }];
        [self.shadowView setAlpha:0];
        self.isClosed = NO;
    }else{
        [UIView animateWithDuration:0.3 animations:^{
            
            [weakSelf.categorty setFrame:KRECT(MDXFrom6(100), MDXFrom6(100), MDXFrom6(150), MDXFrom6(500))];
        }];
        [self.shadowView setAlpha:0.5];
        [self.shadowView addGestureRecognizer:self.tap];
        self.isClosed = YES;
    }
    
    [self.categorty setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:self.shadowView];
    [self.moneyField resignFirstResponder];
    [self.addressTextField resignFirstResponder];
    [self.view addSubview:self.categorty];
}

- (void) setUpCategoryButtonTitle{
    
    __weak typeof(self) weakSelf = self;
    self.categorty.sendTitleTo = ^(NSString *title){
       
        [weakSelf.categoryButton setTitle:title forState:(UIControlStateNormal)];
        [weakSelf.moneyField setPlaceholder:[NSString stringWithFormat:@"%@费用",title]];
        weakSelf.isClosed = YES;
        [weakSelf.categoryButton sendActionsForControlEvents:(UIControlEventTouchUpInside)];
    };
}

// textField
- (UITextField *) setUpMoneyTextFieldWith:(NSString *)placerHolder And:(CGRect) rect{
    
    self.moneyField = [[UITextField alloc] initWithFrame:rect];
    [self.moneyField setDelegate:self];
    [self.moneyField setPlaceholder:[NSString stringWithFormat:@"%@费用",placerHolder]];
    [self.moneyField setTextColor:[UIColor blueColor]];
    [self.moneyField setReturnKeyType:UIReturnKeyNext];
    
    // 数据库,储存其他
    self.account.rests = self.moneyField.text;
    return  self.moneyField;
}

// -- 发生地
- (UITextField *) setUpAddressTextField{
    self.addressTextField = [[UITextField alloc] initWithFrame:KRECT(10, 0, KScreenWidth - 20, 44)];
    [self.addressTextField setDelegate:self];
    [self.addressTextField setPlaceholder:@"地址"];
    [self.addressTextField setTextColor:[UIColor blueColor]];
    [self.addressTextField setReturnKeyType:(UIReturnKeyNext)];
    
    // 数据库,储存地址
    self.account.address = self.addressTextField.text;
    return self.addressTextField;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && indexPath.row == 2) {
        HSDatePickerViewController *hsdpvc = [[HSDatePickerViewController alloc] init];
        [self.addressTextField resignFirstResponder];
        [self.moneyField resignFirstResponder];
        [hsdpvc setDelegate:self];
        if (self.selectedDate) {
            hsdpvc.date = self.selectedDate;
        }
        [self.navigationController pushViewController:hsdpvc animated:YES];
    }else if (indexPath.row == 3 && indexPath.section == 0){
        MoneyTypeViewController *moneyType = [[MoneyTypeViewController alloc] init];
        __weak typeof(self) weakSelf = self;
        [moneyType setSendToStringType:^(NSString *type) {
            weakSelf.typeLabel.text = type;
            NSLog(@"-----------%@",weakSelf.typeLabel.text);
            
            [[FMDBModel defaultFMDBModel]UpdataAccountCategory:nil withNewCategory:nil UpdataAccountRests:nil withNewRests:nil UpdataAccountAddress:nil withNewAddress:nil UpdataAccountTime:nil withNewTime:nil UpdataAccountType:@"CNY 人民币" withNewType:weakSelf.typeLabel.text UpdataAccountTotal:nil withNewTotal:nil UpdataAccountConsumption:nil withNewConsumption:nil];
            
            
        }];
        
        [self.addressTextField resignFirstResponder];
        
        [self.moneyField resignFirstResponder];
        
        moneyType.getString = self.typeLabel.text;
        
        [self.navigationController pushViewController:moneyType animated:YES];
    }
}

#pragma mark - HSDatePickerViewControllerDelegate
- (void)hsDatePickerPickedDate:(NSDate *)date {
    NSLog(@"Date picked %@", date);
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY年MM月dd日 HH:mm:ss"];
    NSString *string = [dateFormatter stringFromDate:date];
    [self.timeLable setText:[NSString stringWithFormat:@"%@",string]];
    self.selectedDate = date;
}


- (void)hsDatePickerDidDismissWithQuitMethod:(HSDatePickerQuitMethod)method {}
//optional
- (void)hsDatePickerWillDismissWithQuitMethod:(HSDatePickerQuitMethod)method {}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

// 点击空白处回收键盘
-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [self.totalField resignFirstResponder];
    [self.consumptionField resignFirstResponder];
    [self.moneyField resignFirstResponder];
}



@end
